import json
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import mixins, viewsets, filters, authentication, permissions
from rest_framework.filters import SearchFilter
from rest_framework.pagination import PageNumberPagination
from itertools import chain
from rest_framework_jwt.authentication import JSONWebTokenAuthentication

from city.models import China
from report.filters import InvolverInfoFilter, MigrantsInfoFilter, PartyFilter
from report.models import InvolverInfo, MigrantsInfo, Party
from report.serializer import InvolverInfoSerializer, MigrantsInfoSerializer, PartySerializer


class Pagination(PageNumberPagination):
    page_size = 12
    page_size_query_param = 'pageSize'
    page_query_param = "pageIndex"
    max_page_size = 1000000


class InvolverInfoListViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin,
                              mixins.DestroyModelMixin, viewsets.GenericViewSet, mixins.UpdateModelMixin):
    queryset = InvolverInfo.objects.filter(delete_flag=False)  # 数据源
    serializer_class = InvolverInfoSerializer
    pagination_class = Pagination  # 分页
    authentication_classes = (JSONWebTokenAuthentication, authentication.SessionAuthentication)

    def get_permissions(self):
        return []
        if self.action == "create":
            return []
        if self.request.method != 'OPTIONS':
            pass
            return [permissions.IsAuthenticated()]
        return []

    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    filter_class = InvolverInfoFilter
    search_fields = ('name', 'mobile')
    ordering_fields = ('db_id',)

    def deal_city(self, serializer):
        obj = serializer.validated_data
        s = ""
        if obj.get("province_id"):
            province = China.objects.get(id=obj.get("province_id"))
            obj["province_name"] = province.name
            s += province.name + "-"
        if obj.get("city_id"):
            city = China.objects.get(id=obj.get("city_id"))
            obj["city_name"] = city.name
            s += city.name + "-"
        if obj.get("area_id"):
            area = China.objects.get(id=obj.get("area_id"))
            obj["area_name"] = area.name
            s += area.name
        obj["house_address"] = s

    def perform_create(self, serializer):
        self.deal_city(serializer)
        serializer.save()

    def perform_update(self, serializer):
        self.deal_city(serializer)
        serializer.save()

    def perform_destroy(self, instance):
        instance.delete_flag = True
        instance.save()


class MigrantsInfoViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin,
                          mixins.DestroyModelMixin, viewsets.GenericViewSet, mixins.UpdateModelMixin):
    queryset = MigrantsInfo.objects.filter(delete_flag=False)  # 数据源
    serializer_class = MigrantsInfoSerializer
    pagination_class = Pagination  # 分页
    authentication_classes = (JSONWebTokenAuthentication, authentication.SessionAuthentication)
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    filter_class = MigrantsInfoFilter
    search_fields = ('name', 'mobile', 'to_label', 'party__to_label')
    ordering_fields = ('id',)

    def perform_create(self, serializer):
        obj = serializer.validated_data
        obj['from_label'] = self.get_from_label(obj)
        obj['to_label'] = self.get_to_label(obj)
        save = serializer.save()
        json_data = self.request.POST.get('party')
        try:
            loads = json.loads(json_data)
            for i in loads:
                i['migrants'] = save
                if i.get('condition'):
                    if isinstance(i["condition"], str):
                        if str(i["condition"]).lower() == "true":
                            i["condition"] = True
                        else:
                            i["condition"] = False
                try:
                    i.pop("ways")
                except:
                    pass
                try:
                    i.pop("car_number")
                except:
                    pass
                i['from_label'] = self.get_from_label(i)
                i['to_label'] = self.get_to_label(i)
                Party.objects.create(**i)
        except Exception as e:
            print("error")
            print(e.args)
            pass

    def perform_update(self, serializer):
        obj = serializer.validated_data
        obj['from_label'] = self.get_from_label(obj)
        obj['to_label'] = self.get_to_label(obj)
        serializer.save()

    def get_permissions(self):
        return []
        if self.action == "create":
            return []
        if self.request.method != 'OPTIONS':
            pass
            return [permissions.IsAuthenticated()]
        return []

    def perform_destroy(self, instance):
        instance.delete_flag = True
        instance.save()

    def get_from_label(self, obj):
        try:
            province_name = ""
            city_name = ""
            area_name = ""
            if obj.get('from_province_id'):
                province = China.objects.get(id=obj.get('from_province_id'))
                province_name = province.name
            if obj.get('from_city_id'):
                city = China.objects.get(id=obj.get('from_city_id'))
                city_name = city.name
            if obj.get('from_area_id'):
                area = China.objects.get(id=obj.get('from_area_id'))
                area_name = area.name
            name_ = "%s-%s-%s" % (province_name, city_name, area_name)
            return name_
        except Exception as e:
            print(e.args)
            return ""

    def get_to_label(self, obj):
        try:
            province_name = ""
            city_name = ""
            area_name = ""
            if obj.get('to_province_id'):
                province = China.objects.get(id=obj.get('to_province_id'))
                province_name = province.name
            if obj.get('to_city_id'):
                city = China.objects.get(id=obj.get('to_city_id'))
                city_name = city.name
            if obj.get('to_area_id'):
                area = China.objects.get(id=obj.get('to_area_id'))
                area_name = area.name
            name_ = "%s-%s-%s" % (province_name, city_name, area_name)
            return name_
        except Exception as e:
            print(e.args)
            return ""


class PartyViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin,
                   mixins.DestroyModelMixin, viewsets.GenericViewSet, mixins.UpdateModelMixin):
    queryset = Party.objects.filter(delete_flag=False)  # 数据源
    serializer_class = PartySerializer
    pagination_class = Pagination  # 分页
    authentication_classes = (JSONWebTokenAuthentication, authentication.SessionAuthentication)
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    filter_class = PartyFilter

    def perform_destroy(self, instance):
        instance.delete_flag = True
        instance.save()

    def perform_create(self, serializer):
        obj = serializer.validated_data
        obj['from_label'] = self.get_from_label(obj)
        obj['to_label'] = self.get_to_label(obj)
        serializer.save()

    def perform_update(self, serializer):
        obj = serializer.validated_data
        obj['from_label'] = self.get_from_label(obj)
        obj['to_label'] = self.get_to_label(obj)
        serializer.save()

    # search_fields = ('name', 'mobile')
    # ordering_fields = ('id',)

    def get_permissions(self):
        return []
        if self.action == "create":
            return []
        if self.request.method != 'OPTIONS':
            return [permissions.IsAuthenticated()]
        return []

    def get_from_label(self, obj):
        try:
            province_name = ""
            city_name = ""
            area_name = ""
            if obj.get('from_province_id'):
                province = China.objects.get(id=obj.get('from_province_id'))
                province_name = province.name
            if obj.get('from_city_id'):
                city = China.objects.get(id=obj.get('from_city_id'))
                city_name = city.name
            if obj.get('from_area_id'):
                area = China.objects.get(id=obj.get('from_area_id'))
                area_name = area.name
            name_ = "%s-%s-%s" % (province_name, city_name, area_name)
            return name_
        except Exception as e:
            print(e.args)
            return ""

    def get_to_label(self, obj):
        try:
            province_name = ""
            city_name = ""
            area_name = ""
            if obj.get('to_province_id'):
                province = China.objects.get(id=obj.get('to_province_id'))
                province_name = province.name
            if obj.get('to_city_id'):
                city = China.objects.get(id=obj.get('to_city_id'))
                city_name = city.name
            if obj.get('to_area_id'):
                area = China.objects.get(id=obj.get('to_area_id'))
                area_name = area.name
            name_ = "%s-%s-%s" % (province_name, city_name, area_name)
            return name_
        except Exception as e:
            print(e.args)
            return ""


